from django.shortcuts import render, HttpResponse
import json
from django.views import View
from app01 import models
from django.conf import settings


class BaseResponse(object):
    def __init__(self):
        self.status = 100
        self.data = None
        self.msg = None


class ServerView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'server.html')


class ServerJsonView(View):
    '''
    为前端返回json格式的数据
    '''
    def get(self, request, *args, **kwargs):
        response = BaseResponse()
        try:
            # 获取要显示的列
            # 获取数据
            table_conf = settings.TABLE_CONF_SERVER

            values_list = []
            for row in table_conf:
                if row['q']:
                    values_list.append(row['q'])

            data_list = models.Server.objects.values(*values_list)

            data_list = list(data_list)
            # print(data_list)
            response.data = {
                'table_conf': table_conf,
                'data_list': data_list
            }
        except Exception as e:
            response.status = 101
            response.msg = str(e)

        return HttpResponse(json.dumps(response.__dict__))


class UserView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'userinfo.html')


class UserJsonView(View):
    def get(self, request, *args, **kwargs):
        response = BaseResponse()
        try:
            # 获取要显示的列
            # 获取数据
            table_conf = settings.TABLE_CONF_USERINFO

            values_list = []
            for row in table_conf:
                if row['q']:
                    values_list.append(row['q'])

            data_list = models.UserInfo.objects.values(*values_list)

            data_list = list(data_list)
            # print(data_list)
            response.data = {
                'table_conf': table_conf,
                'data_list': data_list
            }
        except Exception as e:
            response.status = 101
            response.msg = str(e)

        return HttpResponse(json.dumps(response.__dict__))
